package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha() {
        // 创建验证码对象
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 6);

        // Captcha.TYPE_DEFAULT 表示使用数字和字母混合
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);

        // 生成验证码文本内容，并转换为小写字母（通常用于忽略大小写验证）
        String code = specCaptcha.text().toLowerCase();

        // 生成唯一的Redis存储键，格式为：admin:login:captcha: + UUID
        // UUID.randomUUID() 生成全局唯一标识符，确保每个验证码都有唯一的key
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();

        // 将验证码图片转换为Base64编码字符串，便于前端直接显示
        // 前端可以使用 <img src="data:image/png;base64,{base64字符串}"> 显示图片
        String image = specCaptcha.toBase64();

        // 将验证码文本存储到Redis中，并设置过期时间
        // key ： admin:login: + UUID    value : code
        // set(key, value, timeout, timeUnit) 设置键值对并指定过期时间
        redisTemplate.opsForValue().set(
                key,                    // Redis键
                code,                   // 验证码值
                RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC,  // 过期时间（秒）
                TimeUnit.SECONDS        // 时间单位（秒）
        );

        // 返回包含Base64图片和Redis键的验证码值对象
        // CaptchaVo 应该是一个包含image和key字段的数据传输对象
        return new CaptchaVo(image, key);
    }

    @Override
    public String login(LoginVo loginVo) {
        //1.判断是否输入了验证码
//        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
//            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
//        }
        Assert.notNull(loginVo.getCaptchaCode(), String.valueOf(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND));

        //2.校验验证码
        String code = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }


        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }


        //3.校验用户是否存在 此时存在密码无法查询的问题
        /*LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        SystemUser systemUser = systemUserMapper.selectOne(queryWrapper);
        此时存在密码无法查询的问题
        */
        SystemUser systemUser = systemUserMapper.selectOneName(loginVo.getUsername());
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        //4.校验用户是否被禁
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //5.校验用户密码
        // 密码进行MD5加密，再与数据库中的密码进行验证
        // 注意此时密码设置了保护状态，systemUserMapper.selectOne(queryWrapper);应该改为自定义查询方法
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //6.创建并返回TOKEN
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());

    }

    @Override
    public SystemUserInfoVo infoById(Long userId) {
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        SystemUser systemUser = systemUserMapper.selectById(userId);
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
